<template>
  <transition name="el-zoom-in-center">
  <div>
    <div class="btns">
      <template>
        <el-button type="success" v-hasPermi="['completeWorkflowTask']"  @click="handleButton('办理','bl')">办 理</el-button>
        <el-button type="primary" v-hasPermi="['delegateWorkflowTask']"  @click="handleButton('委办','wb')">委 办</el-button>
        <el-button type="warning" v-hasPermi="['transferWorkflowTask']"  @click="handleButton('转办','zb')">转 办</el-button>
      </template>
      <el-button type="danger" v-hasPermi="['stopWorkflowTask']"   @click="handleButton('终止','zz')">终 止</el-button>
      <el-button @click="goBackToDoWorkflow(true)">返 回</el-button>
    </div>

    <!-- 办理弹窗 -->
    <el-dialog :title="handleTitle" :visible.sync="handleOpen" width="800px" append-to-body>
      <el-form ref="handleForm" :model="handleForm" label-width="80px">
        <el-form-item v-if="this.handleAction==='wb' || this.handleAction==='zb'" :label="handleTitle+'给'" prop="userId" :rules="{required: true, message: handleTitle+'人必须选择'}">
          <el-input style="display: none" v-model="handleForm.userId"/>
          <el-input disabled v-model="handleForm.name" :placeholder="'请选择'+handleTitle+'人'" />
          <el-button type="primary"  size="mini" icon="el-icon-search" @click="addApprover">选择{{handleTitle}}人</el-button>
        </el-form-item>

        <el-form-item ref="comment" :label="handleTitle+'说明'" prop="comment" :rules="{required: true, message: handleTitle+'说明必须填写', trigger: 'blur'}">
          <el-input :hide-required-asterisk="true" type="textarea" :rows="3"  autocomplete="off" v-model="handleForm.comment" :placeholder="'请输入'+handleTitle+'说明'" />
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandleForm">确 定</el-button>
        <el-button @click="cancelHandleOpen">取 消</el-button>
      </div>
    </el-dialog>

    <el-tabs v-model="activeName" @tab-click="handleClickTab">
      <el-tab-pane label="流程详情" name="workflowDetails">
        <div class="">
          <Parser v-if="startParser"
                  :key="parserKey"
                  :form-model="formModel"
                  :label-form-model="labelFormModel"
                  :form-conf="formConf" @next="nextPage" @prev="prevPage" @submit="submitForm"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="流转记录" name="circulationRecord">
        <el-col>
          <div class="block">
            <el-timeline>
              <el-timeline-item
                style="left: 1px"
                v-for="(item,index ) in workflowHistoryRecordList"
                :key="index"
                :icon="setIcon(item.finishTime)"
                :color="setColor(item.finishTime)"
              >
                <p style="font-weight: 700">{{item.taskName}}</p>
                <el-card :body-style="{ padding: '10px' }">
                  <label v-if="item.assigneeName" style="font-weight: normal;margin-right: 30px;">实际办理： {{item.assigneeName}} <el-tag v-if="item.startDeptName" type="info" size="mini">{{item.startDeptName}}</el-tag></label>
                  <label v-if="item.candidate" style="font-weight: normal;margin-right: 30px;">候选办理： {{item.candidate}}</label>
                  <label style="font-weight: normal">接收时间： </label><label style="color:#8a909c;font-weight: normal">{{item.createTime}}</label>
                  <label v-if="item.finishTime" style="margin-left: 30px;font-weight: normal">办结时间： </label><label style="color:#8a909c;font-weight: normal">{{item.finishTime}}</label>
                  <label v-if="item.duration" style="margin-left: 30px;font-weight: normal">耗时： </label><label style="color:#8a909c;font-weight: normal">{{item.duration}}</label>

                  <p style="padding-top: 8px;"  v-if="item.commentDtoList"  v-for="(comment,index) in item.commentDtoList">
                    <el-tag type="success" v-if="comment.type === '1'">  {{comment.comment}}</el-tag>
                    <el-tag type="danger" v-if="comment.type === '2'">  {{comment.comment}}</el-tag>
                    <el-tag type="danger" v-if="comment.type === '3'">  {{comment.comment}}</el-tag>
                    <el-tag type="warning" v-if="comment.type === '4'">  {{comment.comment}}</el-tag>
                    <el-tag type="warning" v-if="comment.type === '5'">  {{comment.comment}}</el-tag>
                    <el-tag type="danger" v-if="comment.type === '6'">  {{comment.comment}}</el-tag>
                    <el-tag type="primary" v-if="comment.type === '7'">  {{comment.comment}}</el-tag>
                    <el-tag type="danger" v-if="comment.type === '8'">  {{comment.comment}}</el-tag>
                  </p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-col>
      </el-tab-pane>
      <el-tab-pane label="流程进度" name="workflowChart">
        <div style="text-align: center;height: 100%;">
          <img :src="workflowRecordPreviewImage" class="image-item" />
        </div>
      </el-tab-pane>
    </el-tabs>

    <userDialog
      :is-multiple-user="false"
      :visible.sync="approverVisible"
      :data.sync="checkedList"
      @change="sureApprover"
    />
  </div>
  </transition>
</template>
<script>
  import userDialog from '@/components/DuoJuHe/Common/dialog/userDialog'
  import Parser from '@/components/DuoJuHe/Form/parser/Parser'
  import {dbDataConvertForItemJson,pageShowHandle,checkAddNumberByItemType} from '@/utils/form/utils/convert'
  import _ from 'lodash'
  import {
    queryMyWorkflowRecordDetailsEditResByRecordId,
    queryWorkflowHistoryRecordPageResLisByRecordId,
    completeWorkflowTask,
    queryWorkflowRecordReadImage,
    transferWorkflowTask,
    delegateWorkflowTask,
    stopWorkflowTask
  } from '@/api/workflow/workflowRecord'
  export default {
    name: "handleWorkflow",
    components: {
      Parser,
      userDialog
    },
    props: {
      recordId: {
        type: String
      },
      projectId: {
        type: String
      },
      taskId: {
        type: String
      },
    },
    data() {
      return {
        approverVisible: false,
        //选中的值
        checkedList:[],
        //流程详情tab默认定位
        activeName: 'workflowDetails',
        // 遮罩层
        loading: true,
        // 弹出层标题
        handleTitle: "",
        //办理方法
        handleAction:undefined,
        // 是否显示新增修改弹出层
        handleOpen: false,
        // 增加修改表单参数
        handleForm: {userId:"",comment:""},
        //流程图片图片
        workflowRecordPreviewImage: "",
        logicItemMap:undefined,
        logicShowTriggerRule: {},
        startParser: false,
        formModel: {},
        labelFormModel: {},
        projectTheme: {
          headImage: '',
          logoImage: '',
          backgroundImg:'',
          showTitle: true,
          showDescribe: true
        },
        parserKey: +new Date(),
        // 每页数据
        perPageFields: {},
        // 流程流转数据
        workflowHistoryRecordList: [],
        formConf: {
          fields: [],
          logicShowRule: {},
          projectId: '',
          projectKind: 1,
          __methods__: {},
          formRef: 'elForm',
          formModel: 'formData',
          labelFormModel: 'labelFormData',
          size: 'small',
          labelPosition: 'top',
          labelWidth: 100,
          formRules: 'rules',
          gutter: 15,
          disabled: true,
          span: 24,
          formBtns: false,
          resetBtn: false,
          submitBtnText: '',
          showNumber: true,
          unFocusedComponentBorder: true
        }
      };
    },
    beforeCreate() {
      document.querySelector('body').className = 'project-body'
    },
    created() {
      //显示流程图片
      this.queryWorkflowRecordPreviewImage();
    },
    mounted() {
      //查询我的流程记录表单详情
      this.queryMyWorkflowRecordDetailsEditResByRecordId();
      //查询历史流转详情
      this.queryWorkflowHistoryRecordPageResLisByRecordId();
    },
    methods: {
      //切换tab
      handleClickTab(tab, event) {
        let activeName = this.activeName;
        if ('circulationRecord'===activeName){
          //查询历史流转详情
          this.queryWorkflowHistoryRecordPageResLisByRecordId();
        }else  if ('workflowChart'===activeName){
          //显示流程图片
          this.queryWorkflowRecordPreviewImage();
        }else {
          //查询我的流程记录表单详情
          this.queryMyWorkflowRecordDetailsEditResByRecordId();
        }
      },
      //弹出联系人弹窗
      addApprover() {
        this.approverVisible = true;
        this.checkedList = []
      },
      //确认选择
      sureApprover(data) {
        this.checkedList = data;
        if (this.checkedList.length===0){
          this.$modal.msgWarning("必须选择一个人员!")
          return
        }else if (this.checkedList.length>1){
          this.$modal.msgError("抱歉只允许选择一个人员!")
          return
        }
        let resultData = this.checkedList[0];
        console.log(resultData)
        this.handleForm.name = resultData.name;
        this.handleForm.userId = resultData.targetId;
        this.approverVisible = false;
      },

      //办理转办等按钮
      handleButton(title,action){
        this.resetForm('handleForm');
        this.handleAction = action;
        this.handleTitle = title;
        this.handleOpen = true;
      },
      // 取消修改增加弹出层按钮
      cancelHandleOpen() {
        this.handleOpen = false
      },
      // 提交办理表单
      submitHandleForm(){
        this.$refs["handleForm"].validate(valid => {
          if (valid) {
            //请求方法
            let handleAction = this.handleAction;
            if(!handleAction){
              this.$modal.msgError("操作参数错误!")
              return
            }
            if("bl"===handleAction){
              const taskComplete={"taskId":this.taskId,"comment":this.handleForm.comment,"recordId":this.recordId}
              //办理
              this.completeWorkflowTask(taskComplete);
            }else  if("wb"===handleAction){
              const taskDelegate={"taskId":this.taskId,"comment":this.handleForm.comment,"delegateToUserId":this.handleForm.userId,"recordId":this.recordId}
              //委办
              this.delegateWorkflowTask(taskDelegate);
            }else  if("zb"===handleAction){
              const taskTransfer={"taskId":this.taskId,"comment":this.handleForm.comment,"transferToUserId":this.handleForm.userId,"recordId":this.recordId}
              //转办
              this.transferWorkflowTask(taskTransfer);
            }else  if("zz"===handleAction){
              const taskStop={"taskId":this.taskId,"comment":this.handleForm.comment,"recordId":this.recordId}
              //终止
              this.stopWorkflowTask(taskStop);
            }
          }
        });
      },
      /** 处理任务 */
      completeWorkflowTask(taskComplete) {
        this.$confirm('确认办理?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          return completeWorkflowTask(taskComplete);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.goBackToDoWorkflow(true);
        }).catch(function() {});
      },

      /** 转办任务 */
      transferWorkflowTask(taskTransfer) {
        this.$confirm('确认转办?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          return transferWorkflowTask(taskTransfer);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.goBackToDoWorkflow(true);
        }).catch(function() {});
      },

      /** 委派任务 */
      delegateWorkflowTask(taskDelegate) {
        this.$confirm('确认委派?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          return delegateWorkflowTask(taskDelegate);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.goBackToDoWorkflow(true);
        }).catch(function() {});
      },


      /** 终止任务 */
      stopWorkflowTask(taskStop) {
        this.$confirm('确认终止?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          return stopWorkflowTask(taskStop);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.goBackToDoWorkflow(true);
        }).catch(function() {});
      },

      //流程图片
      queryWorkflowRecordPreviewImage() {
        const recordId={recordId:this.recordId}
        queryWorkflowRecordReadImage(recordId).then(res => {
          this.workflowRecordPreviewImage = res.data;
        });
      },
      //beg
      queryMyWorkflowRecordDetailsEditResByRecordId(){
        //beg
        const recordId={recordId:this.recordId}
        queryMyWorkflowRecordDetailsEditResByRecordId(recordId).then(res => {
          if (res.data) {
            let data = res.data
            if (data.originalData){
              this.formModel = JSON.parse(data.originalData)
            }
            if (data.processData){
              this.labelFormModel = JSON.parse(data.processData)
            }
            let serialNumber = 1
            let fields = data.formProjectItemResList.map(item => {
              let projectItem = dbDataConvertForItemJson(item)
              projectItem.serialNumber = serialNumber
              projectItem.logicShow = true
              if (checkAddNumberByItemType(item.type)){
                serialNumber++
              }
              return projectItem
            })
            //处理分页数据
            this.perPageFields = pageShowHandle(fields)

            if (_.keys(this.perPageFields).length != 0) {
              this.formConf.fields = _.get(this.perPageFields, 1)
              this.formConf.formBtns = false
            } else {
              this.formConf.fields = fields
            }
            if (data.formProjectRes) {
              let formProjectRes = data.formProjectRes
              this.formConf.title = formProjectRes.projectName
              this.formConf.description = formProjectRes.description
            }
            this.formConf.logicShowRule = this.logicShowTriggerRule
            this.startParser = true
          }
        })
        //end
      },
      //历史流转记录
      queryWorkflowHistoryRecordPageResLisByRecordId(){
        //beg
        const recordId={recordId:this.recordId}
        queryWorkflowHistoryRecordPageResLisByRecordId(recordId).then(res => {
          this.workflowHistoryRecordList = res.data.records
        })
        //end
      },


      //设置icon
      setIcon(val) {
        if (val) {
          return "el-icon-check";
        } else {
          return "el-icon-time";
        }
      },
      //设置颜色
      setColor(val) {
        if (val) {
          return "#2bc418";
        } else {
          return "#b3bdbb";
        }
      },
      //返回
      goBackToDoWorkflow(isRefresh) {
        this.$emit('close', isRefresh);
      },
      /**
       * 处理逻辑显示数据
       */
      prevPage(params) {
        this.switchPage(params.page - 1, params)
      },
      nextPage(params) {
        this.switchPage(params.page + 1, params)
      },
      switchPage(page, params) {
        let {labelFormModel, formModel} = params
        this.formModel = formModel
        this.labelFormModel = labelFormModel
        this.formConf.formBtns = _.keys(this.perPageFields).length == page
        this.formConf.fields = _.get(this.perPageFields, page)
        this.parserKey = +new Date()
      },
      submitForm(data) {
        this.$emit('submit', data)
      }

      //end
    }
  };
</script>
<style lang="scss" scoped>
  /* 图片原图大小自适应 等比缩放 */
  .image-item {
    max-width: 100%;
    max-height: 100%;
  }

  .btns {
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 100;
  }
</style>
